<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>09_拖拽一个盒子</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      body {
        width: 100%;
        height: 1000px;
      }

      div {
        width: 100px;
        height: 100px;
        background-color: pink;
        position: absolute;
        left: 100px;
        top: 100px;
      }
    </style>
  </head>

  <body>
    <div id="box"></div>

    <script>
      var box = document.getElementById("box");

      /* 
        down下鼠标开始拖拽盒子box
        抬起鼠标停止拖拽
        尝试将box放在一个div牲口栏中 让box的拖拽无法超出牲口栏（选做）
        */

      // 记录盒子是否应该跟着鼠标跑
      var shouldFollow = false;

      // down下鼠标开始拖拽盒子box
      box.onmousedown = function (e) {
        shouldFollow = true;
      };

      document.onmousemove = function (e) {
        if (shouldFollow) {
          var left;
          var maxLeft = window.innerWidth - 100;

          left = e.pageX;
          e.pageX < 0 && (left = 0);
          e.pageX > maxLeft && (left = maxLeft);

          var top;
          var maxTop = window.innerHeight - 100;
          console.log("e.pageY", e.pageY);

          top = e.pageY;
          e.pageY < 0 && (top = 0);//-30
        // top = e.pageY > maxTop ? maxTop : e.pageY
          e.pageY > maxTop && (top = maxTop);

          // 鼠标移动到哪里，盒子就跟随到哪里
          box.style.left = left + "px";
          box.style.top = top + "px";
        }
      };

      document.onmouseup = function (e) {
        shouldFollow = false;
      };
    </script>
  </body>
</html>
